<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MPW 算法测试</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 2rem;
            background-color: #f5f5f5;
        }
        .test-card {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 1rem;
        }
        .test-result {
            background: #f0f9ff;
            border: 1px solid #0ea5e9;
            padding: 1rem;
            border-radius: 4px;
            margin: 1rem 0;
        }
        .success {
            background: #f0fdf4;
            border-color: #22c55e;
            color: #166534;
        }
        .error {
            background: #fef2f2;
            border-color: #ef4444;
            color: #dc2626;
        }
        button {
            background: #2563eb;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            margin: 0.5rem 0.5rem 0.5rem 0;
        }
        button:hover {
            background: #1d4ed8;
        }
        input, select {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #d1d5db;
            border-radius: 4px;
            margin: 0.5rem 0;
        }
        .password-output {
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 1.2rem;
            background: #1f2937;
            color: #f9fafb;
            padding: 1rem;
            border-radius: 4px;
            word-break: break-all;
            margin: 1rem 0;
        }
    </style>
</head>
<body>
    <h1>MPW 密码管理器算法测试</h1>
    
    <div class="test-card">
        <h2>算法自测试</h2>
        <p>测试 MPW 算法是否正确实现</p>
        <button onclick="runSelfTest()">运行自测试</button>
        <div id="self-test-result"></div>
    </div>

    <div class="test-card">
        <h2>密码生成测试</h2>
        <div>
            <label>用户名:</label>
            <input type="text" id="test-username" value="testuser" placeholder="输入用户名">
        </div>
        <div>
            <label>主密码:</label>
            <input type="password" id="test-password" value="testpassword" placeholder="输入主密码">
        </div>
        <div>
            <label>网站:</label>
            <input type="text" id="test-site" value="example.com" placeholder="输入网站域名">
        </div>
        <div>
            <label>计数器:</label>
            <input type="number" id="test-counter" value="1" min="1">
        </div>
        <div>
            <label>模板:</label>
            <select id="test-template">
                <option value="maximum">最大强度</option>
                <option value="long" selected>长密码</option>
                <option value="medium">中等长度</option>
                <option value="basic">基础密码</option>
                <option value="short">短密码</option>
                <option value="pin">数字PIN</option>
                <option value="name">用户名</option>
                <option value="phrase">密码短语</option>
            </select>
        </div>
        <div>
            <label>上下文 (可选):</label>
            <input type="text" id="test-context" placeholder="输入上下文">
        </div>
        
        <button onclick="generateTestPassword()">生成密码</button>
        <button onclick="copyPassword()">复制密码</button>
        
        <div id="password-result"></div>
    </div>

    <div class="test-card">
        <h2>性能测试</h2>
        <p>测试密钥生成和密码生成的性能</p>
        <button onclick="runPerformanceTest()">运行性能测试</button>
        <div id="performance-result"></div>
    </div>

    <script src="/mpw/pbkdf2.js"></script>
    <script src="/mpw/scrypt.js"></script>
    <script src="/mpw/mpw.js"></script>
    
    <script>
        // 设置 setImmediate polyfill
        if (!window.setImmediate) {
            window.setImmediate = (callback) => setTimeout(callback, 0);
        }

        async function runSelfTest() {
            const resultDiv = document.getElementById('self-test-result');
            resultDiv.innerHTML = '<div class="test-result">运行中...</div>';
            
            try {
                await MPW.test();
                resultDiv.innerHTML = '<div class="test-result success">✅ 自测试通过！MPW 算法实现正确。</div>';
            } catch (error) {
                resultDiv.innerHTML = `<div class="test-result error">❌ 自测试失败: ${error.message}</div>`;
            }
        }

        async function generateTestPassword() {
            const resultDiv = document.getElementById('password-result');
            resultDiv.innerHTML = '<div class="test-result">生成中...</div>';
            
            try {
                const username = document.getElementById('test-username').value;
                const password = document.getElementById('test-password').value;
                const site = document.getElementById('test-site').value;
                const counter = parseInt(document.getElementById('test-counter').value);
                const template = document.getElementById('test-template').value;
                const context = document.getElementById('test-context').value;
                
                if (!username || !password || !site) {
                    throw new Error('请填写用户名、主密码和网站');
                }
                
                const mpw = new MPW(username, password);
                const generatedPassword = await mpw.generateAuthentication(
                    site, 
                    counter, 
                    context || '', 
                    template
                );
                
                resultDiv.innerHTML = `
                    <div class="test-result success">
                        <h3>生成成功！</h3>
                        <div class="password-output" id="generated-password">${generatedPassword}</div>
                        <p><strong>参数:</strong></p>
                        <ul>
                            <li>用户名: ${username}</li>
                            <li>网站: ${site}</li>
                            <li>计数器: ${counter}</li>
                            <li>模板: ${template}</li>
                            ${context ? `<li>上下文: ${context}</li>` : ''}
                        </ul>
                    </div>
                `;
            } catch (error) {
                resultDiv.innerHTML = `<div class="test-result error">❌ 生成失败: ${error.message}</div>`;
            }
        }

        async function copyPassword() {
            const passwordElement = document.getElementById('generated-password');
            if (!passwordElement) {
                alert('请先生成密码');
                return;
            }
            
            try {
                await navigator.clipboard.writeText(passwordElement.textContent);
                alert('密码已复制到剪贴板');
            } catch (error) {
                // 降级方案
                const range = document.createRange();
                range.selectNode(passwordElement);
                window.getSelection().removeAllRanges();
                window.getSelection().addRange(range);
                document.execCommand('copy');
                window.getSelection().removeAllRanges();
                alert('密码已复制到剪贴板');
            }
        }

        async function runPerformanceTest() {
            const resultDiv = document.getElementById('performance-result');
            resultDiv.innerHTML = '<div class="test-result">测试中...</div>';
            
            try {
                // 测试密钥生成性能
                const startKey = performance.now();
                const mpw = new MPW('testuser', 'testpassword');
                await mpw.key; // 等待密钥生成完成
                const keyTime = performance.now() - startKey;
                
                // 测试密码生成性能
                const startPassword = performance.now();
                await mpw.generateAuthentication('example.com', 1, '', 'long');
                const passwordTime = performance.now() - startPassword;
                
                // 测试多次密码生成
                const iterations = 10;
                const startMultiple = performance.now();
                for (let i = 0; i < iterations; i++) {
                    await mpw.generateAuthentication(`site${i}.com`, 1, '', 'long');
                }
                const multipleTime = performance.now() - startMultiple;
                
                resultDiv.innerHTML = `
                    <div class="test-result success">
                        <h3>性能测试结果</h3>
                        <ul>
                            <li>密钥生成时间: ${keyTime.toFixed(2)} ms</li>
                            <li>单次密码生成时间: ${passwordTime.toFixed(2)} ms</li>
                            <li>${iterations}次密码生成总时间: ${multipleTime.toFixed(2)} ms</li>
                            <li>平均每次密码生成: ${(multipleTime / iterations).toFixed(2)} ms</li>
                        </ul>
                        <p><em>注意: 密钥生成是一次性操作，后续密码生成会很快。</em></p>
                    </div>
                `;
            } catch (error) {
                resultDiv.innerHTML = `<div class="test-result error">❌ 性能测试失败: ${error.message}</div>`;
            }
        }

        // 页面加载时自动运行自测试
        window.addEventListener('load', () => {
            setTimeout(runSelfTest, 500);
        });
    </script>
</body>
</html>
